﻿using CommunityToolkit.HighPerformance.Helpers;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Security;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace PmSoft.RequestHandlers
{
    public class HttpHelper
    {
        ///
        /// Get请求
        /// 
        public HttpWebResponse CreateGetHttpResponse(string url, int timeout = 60, string contentType = "application/json", CookieCollection cookies = null, WebHeaderCollection headers = null, string userAgent = null)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = contentType;
            if (userAgent != null)
            {
                request.UserAgent = userAgent;
            }
            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            if (timeout > 0)
            {
                request.Timeout = timeout * 1000;
            }
            if (headers != null)
            {
                request.Headers.Add(headers);
            }
            request.Timeout = timeout;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            return response;
        }

        ///
        /// Get请求
        /// 
        public string GetHttpResponse(string url, int timeout = 60, string contentType = "application/json", CookieCollection cookies = null, WebHeaderCollection headers = null, string userAgent = null)
        {
            HttpWebResponse response = CreateGetHttpResponse(url, timeout, contentType, cookies, headers, userAgent);
            return GetResponseString(response);
        }

        /// <summary>
        /// 创建POST方式的HTTP请求
        /// timeout 单位（秒/s）
        /// </summary>
        public HttpWebResponse CreatePostHttpResponse(string url, object json, int timeout = 60, string contentType = "application/json", CookieCollection cookies = null, WebHeaderCollection headers = null, string userAgent = null)
        {
            HttpWebRequest request = null;
            if (userAgent != null)
            {
                request.UserAgent = userAgent;
            }
            //如果是发送HTTPS请求  
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            request.Method = "POST";
            request.ContentType = contentType;
            if (timeout > 0)
            {
                request.Timeout = timeout * 1000;
            }
            //设置代理UserAgent和超时
            //request.UserAgent = userAgent;
            //request.Timeout = timeout; 

            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            if (headers != null)
            {
                request.Headers.Add(headers);
            }
            Console.WriteLine("请求路径：" + url);
            //发送POST数据  
            if (json != null)
            {
                var body = "";
                if (typeof(IConvertible).IsAssignableFrom(json.GetType()))
                {
                    body = Convert.ToString(json);
                }
                else
                {
                    body = JsonConvert.SerializeObject(json);
                    // 这里默认 contentType = "application/json" 下面只是简单的处理application/x-www-form-urlencoded
                    if (contentType != null && contentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase))
                    {
                        Dictionary<string, string> d = JsonConvert.DeserializeObject<Dictionary<string, string>>(body);
                        StringBuilder sb = new StringBuilder();
                        foreach (var item in d)
                        {
                            sb.Append("&").Append(item.Key).Append("=").Append(item.Value);
                        }
                        if (sb.Length > 0)
                        {
                            sb.Remove(0, 1);
                        }
                        body = sb.ToString();
                    }
                }
                byte[] data = Encoding.UTF8.GetBytes(body);
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            return request.GetResponse() as HttpWebResponse;
        }



        /// <summary>
        /// 创建POST方式的HTTP请求
        /// </summary>
        public string PostHttpResponse(string url, object json, int timeout = 60, string contentType = "application/json", CookieCollection cookies = null, WebHeaderCollection headers = null, string userAgent = null)
        {
            HttpWebResponse response = CreatePostHttpResponse(url, json, timeout, contentType, cookies, headers, userAgent);
            return GetResponseString(response);
        }

        /// <summary>
        /// 创建POST方式的HTTP请求
        /// </summary>
        public ResponseResult<T> PostHttpResponse<T>(string url, object json, int timeout = 60, string contentType = "application/json", CookieCollection cookies = null, WebHeaderCollection headers = null, string userAgent = null)
        {
            string response = PostHttpResponse(url, json, timeout, contentType, cookies, headers, userAgent);
            Console.WriteLine("POST:" + url + ", 请求结果:" + response);
            if (string.IsNullOrEmpty(response))
            {
                return new ResponseResult<T>();
            }
            var rr = JsonConvert.DeserializeObject<ResponseResult<T>>(response);
            return rr;
        }


        /// <summary>
        /// 获取请求的数据
        /// </summary>
        public string GetResponseString(HttpWebResponse webresponse)
        {
            using (Stream s = webresponse.GetResponseStream())
            {
                StreamReader reader = new StreamReader(s, Encoding.UTF8);
                return reader.ReadToEnd();
            }
        }
    }

    public partial class ResponseResult<T>
    {
        public int c = 500;
        public string m = "未知错误";

        /// <summary>
        /// 返回值编码，参建返回状态编码表
        /// </summary>
        public int code
        {
            get
            {
                return c;
            }
            set
            {
                c = value;
            }
        }

        /// <summary>
        /// 返回提示信息,如具体错误信息
        /// </summary>
        public string msg
        {
            get
            {
                return m;
            }
            set
            {
                m = value;
            }
        }

        /// <summary>
        /// 返回成功时携带的部分数据
        /// </summary>
        public T data { get; set; }
    }
}
